package com.xzz.sort;

import java.util.*;

/**
 * @author: hhz
 * @create: 2021-12-15 14:04
 **/
public class TopKForPriorityQueue {
    public static void main(String[] args) {
        int[] nums = new int[]{1,1,2,2,2,3,4,5,5,5,5};
        int[] arr = topKFrequent(nums, 2);
        System.out.println(Arrays.toString(arr));
    }
    public static int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer,Integer> map = new HashMap();
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            map.put(num,map.getOrDefault(num,0)+1);
        }
        //使用优先队列（二叉小顶堆实现）
        PriorityQueue<Node> priorityQueue = new PriorityQueue<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if(priorityQueue.size()!=k){
                priorityQueue.offer(new Node(entry.getKey(),entry.getValue()));
            }else {
                if(priorityQueue.peek().getValue() < entry.getValue()){
                    priorityQueue.poll();
                    priorityQueue.offer(new Node(entry.getKey(), entry.getValue()));
                }
            }
        }
        int[] res = new int[k];
        for (int i = 0; i < k; ++i) {
            res[i] = priorityQueue.poll().getKey();
        }
        return res;
    }
    static class Node implements Comparable<Node>{
        int key;
        int value;
        public Node(int key,int value){
            this.key = key;
            this.value = value;
        }
        public int getKey() {
            return key;
        }

        public void setKey(int key) {
            this.key = key;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        @Override
        public int compareTo(Node o) {
            return this.value-o.value;
        }
    }
}
